import Base from '@/common/constants/Base'

type value<T> = {
  /**
   * @description 超时时间
   */
  timeout: number | null

  /**
   * @description 缓存数据
   */
  value: T
}

/**
 * @description 本地缓存KEYS
 */
class Storage extends Base {

  /**
   * @description 用户缓存
   */
  public readonly USER: string = "CONSTANT_USER";

  /**
   * @description 设置本地储存
   * @param key 缓存名字
   * @param value 缓存内容
   * @param timeout 过期时间 单位 秒 -- 默认不过期
   */
  public setStorage<T> (key: string, value: T, timeout?: number): void {
    const data: value<T> = {timeout: timeout || null, value };
    localStorage.setItem(key, JSON.stringify(data));
  }

  /**
   * @description 获取本地储存
   * @param key Key
   * @returns 
   */
  public getStorage<T> (key: string): T | null {
    const item = localStorage.getItem(key);
    const data: value<T> = item ? JSON.parse(item) : null;
    const time: number = new Date().getTime();
    let r: T | null = null;

    if (data && data.timeout && data.timeout >= time) {
      this.removeStorage(key);
    } else {
      r = data?.value;
    }

    return r;
  }

  /**
   * @description 移除缓存
   * @param key 
   */
  public removeStorage(key: string): void {
    localStorage.removeItem(key);
  }

  /**
   * @description 清空本地储存
   */
  public clearStorage(): void {
    localStorage.clear();
  }
}

export default new Storage();